using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Linq;

namespace RStein.Posterous.API
{
    internal class SitesResponseParser : IResultResponseParser<IEnumerable<IPosterousSite>>
    {
        public IEnumerable<IPosterousSite> GetResults(Stream stream)
        {
          if (stream == null)
          {
            throw new ArgumentNullException("stream");
          }


          XmlReader reader = XmlReader.Create(stream);
          XElement root = XElement.Load(reader);

          var sites =
              (from elem in root.Elements(GlobalConstants.XML_SITE_ELEMENT)
               select new PosterousSite((int)elem.Element(GlobalConstants.XML_ID_ELEMENT))
                          {
                            Name = elem.Element(GlobalConstants.XML_NAME_ELEMENT).Value,
                            IsPrivate = (bool)elem.Element(GlobalConstants.XML_PRIVATE_ELEMENT),
                            IsPrimary = (bool)elem.Element(GlobalConstants.XML_PRIMARY_ELEMENT),
                            AreCommentsEnabled = (bool)elem.Element(GlobalConstants.XML_COMMENTSENABLED_ELEMENT),
                            TotalPosts = (int)elem.Element(GlobalConstants.XML_NUMPOST_ELEMENT)

                          }).Cast<IPosterousSite>().ToList();

          return sites;
            

        }
    }
}

